import tools from '@/common/utils/tools.js'
import {
	API_URL
} from '@/env';

import vue from 'vue';

import {
	router,
	RouterMount
} from '@/common/router.js';

/**
 * 常量：接口消息结构--数据字段名称
 */
const RES_DATA_FIELD = 'data'; //存储数据的属性名称

/**
 * 常量：接口消息结构--信息字段名称
 */
const RES_INFO_FIELD = 'info'; //存储信息的属性名称
/**
 * 常量：接口消息结构--状态字段名称
 */
const RES_STATUS_FIELD = 'status'; //存储状态的属性名称
/**
 * 常量：接口消息结构--成功状态值
 */
const RES_STATUS_SUCCESS = 1; //成功的状态
/**
 * 常量:接口消息结构--失败状态值
 */
const RES_STATUS_FAIL = 0; //失败的状态

/**
 * 常量:接口消息结构--登陆异常状态值
 */
const RES_STATUS_UNUSUAL = -1; //失败的状态
/**
 * 常量:接口消息结构--无权限状态值
 */
const RES_STATUS_AUTHORITY = -2; //失败的状态
/**
 * 常量:接口消息结构--未认证会员状态值
 */
const RES_STATUS_MEMBER = 2


export default class Request {
	config = {
		baseUrl: API_URL,
		header: {
			'content-type': 'application/json; charset=UTF-8'
		},
		method: 'GET',
		dataType: 'application/json;'
	}

	// 判断URL是否为绝对路径
	static posUrl(url) {
		return /(http|https):\/\/([\w.]+\/?)\S*/.test();
	}
	static addQueryString(params) {
		let paramsData = ''
		Object.keys(params).forEach(function(key) {
			paramsData += key + '=' + encodeURIComponent(params[key]) + '&'
		})
		return paramsData.substring(0, paramsData.length - 1)
	}
	/**
	 * @property {Function} request 请求拦截器
	 * @property {Function} response 响应拦截器
	 * @type {{request: Request.interceptor.request, response: Request.interceptor.response}}
	 */
	interceptor = {
		/**
		 * @param {Request~requestCallback} cb - 请求之前拦截,接收一个函数（config, cancel）=> {return config}。第一个参数为全局config,第二个参数为函数，调用则取消本次请求。
		 */
		request: (cb) => {
			if (cb) {
				this.requestBeforeFun = cb
			}
		},
		/**
		 * @param {Request~responseCallback} cb 响应拦截器，对响应数据做点什么
		 * @param {Request~responseErrCallback} ecb 响应拦截器，对响应错误做点什么
		 */
		response: (cb, ecb) => {
			if (cb && ecb) {
				this.requestComFun = cb
				this.requestComFail = ecb
			}
		}
	}
	requestBeforeFun(config) {
		return config
	}
	requestComFun(response) {
		return response
	}
	requestComFail(response) {
		return response
	}
	/**
	 * 自定义验证器，如果返回true 则进入响应拦截器的响应成功函数(resolve)，否则进入响应拦截器的响应错误函数(reject)
	 * @param { Number } statusCode - 请求响应体statusCode（只读）
	 * @return { Boolean } 如果为true,则 resolve, 否则 reject
	 */
	validateStatus(statusCode) {
		return statusCode === 200
	}
	/**
	 * @Function
	 * @param {Request~setConfigCallback} f - 设置全局默认配置
	 */
	setConfig(f) {
		this.config = f(this.config)
	}
	/**
	 * @param {Object} url 路由跳转
	 */
	router(url, type = 'reLaunch') {
		setTimeout(() => {
			if (type == 'reLaunch') {
				uni.reLaunch({
					url
				})
			}
			if (type == 'push') {
				uni.navigateTo({
					url
				})
			}
		}, 1800)
	}

	/**
	 * @Functions
	 * @param {Object} options - 请求配置项
	 * @prop {String} options.url - 请求路径
	 * @prop {Object} options.data - 请求参数
	 * @prop {Object} [options.responseType = config.responseType] [text|arraybuffer] - 响应数据类型
	 * @prop {Object} [options.dataType = config.dataType] - 如果设置为json，会尝试对返回的做一次 JSON.parse
	 * @prop {Object} [options.header = config.header] - 请求header
	 * @prop {Object} [options.method = config.method] - 请求方法
	 * @return {Promis<unknown>}
	 */
	async request(options = {}) {
		if (options.header) {
			var config = {
				headers: {
					'Contet-Type': options.header
				}
			}
		}
		options.baseUrl = this.config.baseUrl
		options.dataType = options.dataType || this.config.dataType
		options.url = options.url || ''
		options.data = options.data || {}
		options.params = options.params || {}
		options.header = options.header || this.config.header
		options.method = options.method || this.config.method
		options.custom = {
			...this.config.custom,
			...(options.custom || {})
		}
		return new Promise((resolve, reject) => {
			let next = true
			let hendleRe = {}
			options.complete = (response) => {
				// console.log(response,'response')
				response.config = hendleRe;
				// console.log(typeof(response.data) != Object,'typeof(response.data) != Object')
				// console.log(hendleRe,'hendleRe')
				if (typeof(response.data) != Object) {
					let data = JSON.parse(response.data);
					if (response.config.url == "api/auth/loginOut" && data.status == -1) {
						tools.toast('安全退出');
						this.router('/pages/login/index');
						return resolve(response)
					};
					switch (data[RES_STATUS_FIELD]) {
						case RES_STATUS_SUCCESS:
							response = this.requestComFun(response)
							return resolve(response);
							break;
						case RES_STATUS_FAIL:
							response = this.requestComFail(response)
							tools.toast(data.info)
							return reject(response);
							break;
						case RES_STATUS_UNUSUAL:
                            response = this.requestComFail(response)
							tools.toast('用户信息过期，请重新登录')
							this.router('/pages/login/index')
                            return reject(response)
							break;
						case 500:
							response = this.requestComFail(response)
							tools.toast(data.info);
                            return reject(response)
							break;
						case RES_STATUS_AUTHORITY:
							tools.toast(data.info)
							this.router('/pages/user/binding/binding', 'push')
							return;
							default:
                                // 兜底处理，只有提示，没有返回数据
                              tools.toast(data.info)
					}
				}

			}
			const cancel = (t = 'handle cancel', config = options) => {
				const err = {
					errMsg: t,
					config: config
				}
				reject(err)
				next = false
			}
			hendleRe = {
				...this.requestBeforeFun(options, cancel)
			}
			const _config = {
				...hendleRe
			}
			if (!next) return
			delete _config.custom
			let mergeUrl = Request.posUrl(_config.url) ? _config.url : (_config.baseUrl + _config.url)
			if (JSON.stringify(_config.params) !== '{}') {
				const paramsH = Request.addQueryString(_config.params);
				mergeUrl += mergeUrl.indexOf('?') === -1 ? `?${paramsH}` : `&${paramsH}`
			}
			_config.url = mergeUrl
			// 丢给uni-app框架封装好的api接口。 就不用axios了。
			uni.request(_config)
		})
	}
	// 请求方式
	get(url, options = {}) {
		return this.request({
			url,
			method: 'GET',
			...options
		})
	}
	post(url, data, options = {}) {
		return this.request({
			url,
			data,
			method: 'POST',
			...options
		})
	}

}
/**
 * setConfig回调
 * @return {Object} - 返回操作后的config
 * @callback Request~setConfigCallback
 * @param {Objct} config - 全局默认config
 */

/**
 * 请求拦截器回调
 * @return {Object} - 返回操作后的config
 * @callback Request~requestCallback
 * @param {Object} config - 全局config
 * @param {Function} [cancel] - 取消请求钩子，调用会取消本次请求
 */

/**
 * 响应拦截器回调
 * @return {Object} - 返回操作后的response
 * @callback Request~responseCallback
 * @param {Object} response - 请求结果 response
 */

/**
 * 响应错误拦截器回调
 * @return {Object} - 返回操作后的response
 * @callback  Request~responseErrCallback
 * @param {Object} response - 请求结果 response
 */
